import { DataSource } from 'typeorm'
import { mysqlConfig, mongodbConfig } from '@/configs/ormconfig'
// import { MongoDriver } from 'typeorm/driver/mongodb/MongoDriver'
import logger, { consoleLogger } from '../logger'
import { IS_DEV } from '@/constants'
// MYSQL数据库连接
const mysqlDataSource = new DataSource(mysqlConfig)

// MONGODB数据库连接
const mongodbDataSource = new DataSource(mongodbConfig)

// 初始化数据库连接
const initializeDatabaseConnections = async () => {
  try {
    await mysqlDataSource.initialize()
    consoleLogger.info('MYSQL 数据库连接成功')
    await mysqlDataSource.runMigrations()
    consoleLogger.info('MYSQL 数据库迁移成功')
  } catch (e) {
    let message = 'MYSQL 数据库连接失败'
    if (mysqlDataSource.isInitialized) {
      message = 'MYSQL 数据库迁移失败'
    }
    consoleLogger.error(message, e)
    logger.error(message, e)
  }

  try {
    await mongodbDataSource.initialize()
    consoleLogger.info('MONGODB 数据库连接成功')
    await mongodbDataSource.runMigrations()
    consoleLogger.info('MONGODB 数据库迁移成功')
    if (IS_DEV) {
      // 开发环境开启mongodb日志
      // TODO 优化日志输出到文件
      // const conn = (mongodbDataSource.driver as MongoDriver).queryRunner!.databaseConnection
      // conn.on('commandStarted', evt => {
      //   consoleLogger.info(evt)
      // })
      // conn.on('commandFailed', evt => {
      //   consoleLogger.error(evt)
      // })
    }
  } catch (e) {
    let message = 'MONGODB 数据库连接失败'
    if (mongodbDataSource.isInitialized) {
      message = 'MONGODB 数据库迁移失败'
    }
    consoleLogger.error(message, e)
    logger.error(message, e)
  }
}

// 销毁数据库连接
const destroyDatabaseConnections = async () => {
  if (mysqlDataSource.isInitialized) {
    try {
      await mysqlDataSource.destroy()
      consoleLogger.info('MYSQL 数据库连接销毁成功')
    } catch (e) {
      consoleLogger.error('MYSQL 数据库连接销毁失败', e)
      logger.error('MYSQL 数据库连接销毁失败', e)
    }
  }

  if (mongodbDataSource.isInitialized) {
    try {
      await mongodbDataSource.destroy()
      consoleLogger.info('MONGODB 数据库连接销毁成功')
    } catch (e) {
      consoleLogger.error('MONGODB 数据库连接销毁失败', e)
      logger.error('MONGODB 数据库连接销毁失败', e)
    }
  }
}

export { mysqlDataSource, mongodbDataSource, initializeDatabaseConnections, destroyDatabaseConnections }
